package test;

public class UTF8ToAscii {

    public static void main(final String[] args) throws Exception {

        System.out.println("Usage: java UTF8ToAscii <filename>");

        System.out.println(unicodeEscape("Defei🙆你好!𐀀�"));

        System.out.println();

        System.out.println("\uD83D\uDE46");

        // StringEscapeUtils
    }

    private static final char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
            'B', 'C', 'D', 'E', 'F' };

    private static String unicodeEscape(final String s) {

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if ((c >> 15) > 0) {
                sb.append("\\u");
                sb.append(hexChar[(c >> 12) & 0xF]); // append the hex character
                                                     // for the left-most 4-bits
                sb.append(hexChar[(c >> 8) & 0xF]); // hex for the second group
                                                    // of 4-bits from the left
                sb.append(hexChar[(c >> 4) & 0xF]); // hex for the third group
                sb.append(hexChar[c & 0xF]); // hex for the last group, e.g.,
                                             // the right most 4-bits
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}
